import receiveMsg from './receiveMsg.js'
import store from '@/store/index.js'

const ws = new WebSocket('ws:www.huangzikai.club:8888/ws')
ws.onopen = () => {
  console.log('websocket已连接')
}
ws.onmessage = (message) => {
  // 解析消息
  const body = JSON.parse(message.data)
  switch (body.type) {
    case 6: // 有人加你了！
      store.dispatch('getFriendRequestList') // 获取好友请求列表
      store.commit('updateNewFriendCount', {count: 1})
      break
    case 5: // 别人同意你的请求啦！
      store.dispatch('getContacts') // 刷新通讯录
      const currentSession = {
        accepter: body.extend,
        messages: [{
          isMyself: false,
          msg: '我通过了你的朋友验证请求，现在我们可以开始聊天了',
          msgId: ''
        }],
        count: 1
      }
      store.dispatch('updateSessionList', currentSession) // 更新sessionList，push一个会话
      break
    case 2: // 接收到聊天消息
      receiveMsg(body)
      break
  }
}
export default ws
